/**
* 培训查看
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>添加培训</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="margin-top: 20px; width: 800px; border:2px solid #b4bccc">
      <el-row :gutter=20>
        <el-col>
          <div>
            <el-divider content-position="left">基本信息</el-divider>
          </div>
        </el-col>
        <el-form ref="form" :model="form" label-width="80px">
          <el-col :sm="12">
            <div>
              <el-form-item label="培训标题">
                <el-input v-model="form.trainName"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="12">
            <div>
              <el-form-item label="培训等级">
                <el-select v-model="form.garde" filterable placeholder="请选择">
                  <el-option
                    v-for="garde in gardeMenu"
                    :key="garde.dataId"
                    :label="garde.dataName"
                    :value="garde.dataId">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="12">
            <div>
              <el-form-item label="培训状态">
                <el-select v-model="form.status" filterable placeholder="请选择">
                  <el-option
                    v-for="tarinStatus in TrainStatusMenu"
                    :key="tarinStatus.dataId"
                    :label="tarinStatus.dataName"
                    :value="tarinStatus.dataId">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="12">
            <div>
              <el-form-item label="培训类别">
                <el-select v-model="form.trainerCategory" filterable placeholder="请选择">
                  <el-option
                    v-for="item in trainerCategoryMenu"
                    :key="item.dataId"
                    :label="item.dataName"
                    :value="item.dataId">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="12">
            <div>
              <el-form-item label="负责人">
                <el-select v-model="form.managerPerson" filterable placeholder="请选择">
                  <el-option
                    v-for="manager in managerMenu"
                    :key="manager.dataId"
                    :label="manager.dataName"
                    :value="manager.dataId">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="10">
            <div>
              <el-form-item label="培训预算">
                <el-input-number v-model="form.trainerBudget" :min="0" :precision="2" :step="100"
                                 :max="100000000"></el-input-number>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="12">
            <div>
              <el-form-item label="描述">
                <el-input type="textarea" v-model="form.des"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="5" :offset="2">
            <div>
              <el-upload
                class="upload-demo"
                action="/api/qiniu/upload"
                :before-remove="beforeRemove"
                multiple
                :limit="1"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :on-exceed="handleExceed"
                :on-remove="imgRemove"
                :file-list="fileList"
                :headers="uploadHeaders">
                <el-button size="" type="primary">上传封面</el-button>
                <div style="font-size: 14px;" slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </div>
          </el-col>
          <el-col>
            <div>
              <el-divider content-position="left">报名设置</el-divider>
            </div>
          </el-col>
          <el-col :sm="6">
            <div>
              <el-form-item label="报名人数">
                <template>
                  <el-input-number :disabled="isBolg" v-model="form.enrollNum" controls-position="right" :min="-1"
                                   :max="1000000"></el-input-number>
                </template>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="10">
            <div>
              <el-form-item label="">
                <template>
                  <el-switch @change="isEnrollNum"
                             v-model="isBolg"
                             active-text="不限制人数"
                             inactive-text="限制人数">
                  </el-switch>
                </template>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="20">
            <div>
              <el-form-item label="报名形式">
                <el-select v-model="form.enrollForm" filterable placeholder="请选择">
                  <el-option
                    v-for="enrollForm in enrollFormMenu"
                    :key="enrollForm.dataId"
                    :label="enrollForm.dataName"
                    :value="enrollForm.dataId">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div>
              <el-form-item label="截至时间">
                <div class="block">
                  <el-date-picker
                    v-model="form.lastTime"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </div>
              </el-form-item>
            </div>
          </el-col>

          <el-col>
            <div>
              <el-divider content-position="left">培训设置</el-divider>
            </div>
          </el-col>

          <!--          <el-col>
                      <div>
                      </div>
                    </el-col>-->
          <el-col :sm="10" :offset="4">
            <div>
              <el-form-item label="培训地点">
                <el-input v-model="form.enrollAddress"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :sm="3">
            <div style="margin-top: 20px">
              <el-checkbox v-model="isSignIn">是否签到</el-checkbox>
            </div>
          </el-col>
          <el-col :sm="3">
            <div style="margin-top: 20px">
              <el-checkbox v-model="isMasT">是否必修</el-checkbox>
            </div>
          </el-col>
          <el-col :sm="18" :offset="5">
            <div>
              <div class="block">
                <span class="demonstration">开始结束时间</span>
                <el-date-picker
                  v-model="startEndTime"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </div>
            </div>
          </el-col>
          <el-col>
            <div>
              <el-divider></el-divider>
            </div>
          </el-col>
          <el-col :offset="17">
            <div>
              <el-form-item>
                <el-button size="small" type="primary" @click="onSubmit">提交</el-button>
              </el-form-item>
            </div>
          </el-col>
        </el-form>
      </el-row>
    </div>

  </div>
</template>

<script>
export default {
  data() {
    return {
      //是否是编辑
      isTrainEdit: false,
      //是否限制人数
      isBolg: false,
      //报名人数
      enrollNum: '',
      startEndTime: '',
      form: {
        id: '',
        trainName: '',
        des: '',
        trainTime: '',
        trainerCategory: '',
        garde: 1,
        status: 1,
        trainerBudget: '',
        lastTime: '',
        enrollForm: '',
        enrollNum: '',
        startTime: '',
        endTime: '',
        enrollAddress: '',
        isSignin: '',
        managerPerson: '',
        isMust: '',
      },
      uploadHeaders: {}, //表单请求头
      //是否签到的checkBox
      isSignIn: false,

      //是否签到的checkBox
      isMasT: false,
      //培训类别菜单数据
      trainerCategoryMenu: [],
      //培训类别菜单数据
      managerMenu: [],
      //文件上传
      fileList: [],
      //回调的文件名
      trainImgName: null,
      trainImgUrl: null,
      //培训等级菜单数据
      gardeMenu: [{dataId: 1, dataName: '简单'}, {dataId: 2, dataName: '中等'}, {dataId: 3, dataName: '困难'}],
      //培训状态菜单数据
      TrainStatusMenu: [{dataId: 1, dataName: '未开始'}, {dataId: 2, dataName: '进行中'}, {dataId: 3, dataName: '已完成'}],
      //报名形式菜单数据
      enrollFormMenu: [{dataId: 1, dataName: '页面报名'}, {dataId: 2, dataName: '手动添加'}]

    }
  },
  // 注册组件
  components: {},

  /**
   * 数据发生改变
   */
  watch: {},

  /**
   * 创建完毕
   */
  created() {
    this.uploadHeaders = { //设置授权的Token
      'token': localStorage.getItem('Authorization')
    }
    this.getdata()
    let id = this.$route.params.id;
    console.log(id)
    if (id != undefined && id != 'undefined') {
      this.isTrainEdit = true
      this.getEditData(id)
    }
    // this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    getEditData(id) {
      this.$axios.get('/api/train/findTrainByIdEdit/' + id).then(res => {
        console.log(res)
        this.form = res.data.data
        this.startEndTime = [this.form.startTime, this.form.endTime]
        if (this.form.enrollNum === -1) {
          this.isBolg = true
        }
      }).catch()
    },
    onSubmit() {
      this.form.startTime = this.startEndTime[0]
      this.form.endTime = this.startEndTime[1]
      if (this.isSignIn) {
        this.form.isSignin = '2'
      } else {
        this.form.isSignin = '1'
      }
      if (this.isMasT) {
        this.form.isMust = '2'
      } else {
        this.form.isMust = '1'
      }
      this.form.trainTime = (new Date(this.form.endTime).getTime() - new Date(this.form.startTime).getTime()) / (1000 * 3600 * 24)
      console.log(this.form);
      if (this.form.managerPerson == '') {
        this.$message({type: "error", message: "请选择负责人"})
        return;
      }
      if (this.isTrainEdit) {
        console.log(this.form)
        this.$axios.post('/api/train/updateTrain/' + this.trainImgName + '/' + this.trainImgUrl, this.form).then(res => {
          console.log(res)
          if (res.data.code === 200) {
            this.open()
          } else {
            this.$message({
              type: 'error',
              message: '添加失败!'
            })
          }
        }).catch()
      } else {
        this.$axios.post('/api/train/createTrain/' + this.trainImgName + '/' + this.trainImgUrl, this.form).then(res => {
          console.log(res)
          if (res.data.code === 200) {
            this.open()
          } else {
            this.$message({
              type: 'error',
              message: '添加失败!'
            })
          }
        }).catch()
      }

    },

    // 获取数据方法
    getdata() {
      // 获取培训列表
      this.$axios.get('/api/category/findCategoryMenu/')
        .then(res => {
          console.log(res)
          if (res.data.code === 200) {
            this.trainerCategoryMenu = res.data.data
            console.log(this.trainerCategoryMenu)
          }
        }).catch()

      // 获取所有负责人
      this.$axios.get('/api/department/findAllManager/')
        .then(res => {
          console.log(res)
          if (res.data.code === 200) {
            this.managerMenu = res.data.data
            console.log(this.trainerCategoryMenu)
          }
        }).catch()

    },
    isEnrollNum() {
      this.enrollNum = this.form.enrollNum
      if (this.isBolg) {
        this.form.enrollNum = "-1"
      } else {
        this.form.enrollNum = this.enrollNum
      }
      console.log(this.form.enrollNum)
    },
    //确认弹框
    open() {
      this.$confirm('操作成功', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (!this.isTrainEdit) {
          this.clearData()
        }
      }).catch(() => {
        this.$router.push({name: 'findTrain'})
      });
    },
    //初始化数据
    clearData() {
      this.isTrainEdit = false;
      this.isMasT = false
      this.isSignIn = false
      this.isBolg = false
      this.fileList = []
      this.trainImgName = ''
      this.enrollNum = ''
      this.startEndTime = ''
      this.form.id = ''
      this.form.trainName = ''
      this.form.des = ''
      this.form.trainTime = ''
      this.form.trainerCategory = ''
      this.form.garde = '1'
      this.form.status = '1'
      this.form.trainerBudget = ''
      this.form.lastTime = ''
      this.form.enrollForm = ''
      this.form.enrollNum = ''
      this.form.startTime = ''
      this.form.endTime = ''
      this.form.enrollAddress = ''
      this.form.isSignin = ''
      this.form.managerPerson = ''
      this.form.isMust = ''
    },

    handleExceed(files, fileList) {
      this.$message.warning(`只能上传  1 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleUploadPreview(file) {//文件上传进行大小判断
      console.log(file);
      const isLt2M = file.size / 1024 / 1024 < 30;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 25MB!');
      }
      return isLt2M;
    },
    handleUploadSuccess(res, file) {//处理成功后的设置
      console.log(res);
      if (res.code === 200) {
        this.$message.success('上传成功')
        this.trainImgName = res.data.originName
        this.trainImgUrl = res.data.fileName
        console.log(this.trainImgName);
      } else {
        this.$message.success(res.msg)
      }
    },
    handleUploadError(err, file) {
      this.$message.error("失败" + err)
    },
    imgRemove(file, fileList) {
      this.$axios.delete('/api/qiniu/delete/file/' + this.trainImgUrl).then(res => {
        console.log(res)
      })
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}

.userRole {
  width: 100%;
}
</style>

